<template>
  <de-container class="pa-5">
    <avue-crud
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :search.sync="searchForm"
      @on-load="loadListData"
      @search-change="onSearchChange"
      @keyup.enter="onSearchChange"
      @search-reset="onSearchReset"
      @row-save="onRowSave"
      @row-update="onRowUpdate"
      @row-del="onRowDelete"
      @refresh-change="onRefresh"
      @selection-change="onSelectionChange"
      @filter-change="onFilterChange"
      @sort-change="onSortChange"
    >
      <template slot="enabled" slot-scope="{ row, size }">
        <el-switch
          v-loading="row.switching"
          :value="row.enabled"
          :active-value="1"
          :inactive-value="0"
          :size="size"
          @change="onToggleStatus(row)"
        />
      </template>
      <template slot="createTime" slot-scope="{ row }">
        {{ row.createAt || '' }}
      </template>
      <template slot="menu" slot-scope="{ size, row }">
        <el-button type="text" icon="el-icon-refresh" :size="size" @click="onPasswordResetClick(row)">
          重置密码
        </el-button>
      </template>
    </avue-crud>
  </de-container>
</template>

<script>
import moment from 'moment'
import {
  requestUserPage,
  requestUserCreate,
  requestUserUpdate,
  requestUserDelete,
  requestUserPasswordReset,
  requestUserStatusUpdate,
} from '@/api/system/user'
import { defaultPwd } from '@/api/user'
import DeContainer from '@/components/dataease/DeContainer'
import ListMixin from '@/utils/mixins/list-mixin'

const DEFAULT_LIST_MAP_FUNC = (item) => {
  const ret = item
  if (item.createTime) {
    ret.createAt = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
  }
  return ret
}
const DEFAULT_EDIT_MAP_FUNC = (item) => {
  const ret = item
  item.switching = false

  return ret
}

export default {
  name: 'UserList',
  components: { DeContainer },
  mixins: [ListMixin],
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (value.indexOf('@') <= 0 || value.indexOf('@') === value.length - 1) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    return {
      listApi: requestUserPage,
      createApi: requestUserCreate,
      updateApi: requestUserUpdate,
      deleteApi: requestUserDelete,
      listMapFunc: DEFAULT_LIST_MAP_FUNC,
      editMapFunc: DEFAULT_EDIT_MAP_FUNC,
      tableOption: {
        menuWidth: 240,
        addTitle: '新增用户',
        editTitle: '编辑用户',
        viewTitle: '查看用户',
        searchMenuPosition: 'left',
        column: [
          {
            label: '登录名',
            prop: 'username',

            maxlength: 24,
            showWordLimit: true,
            rules: [
              { required: true, message: '请输入登录名' },
              { max: 24, message: '最多24个字' },
            ],
            span: 12,
            align: 'left',
            editDisabled: true,
            overHidden: true,
          },
          {
            label: '用户姓名',
            prop: 'nickName',
            search: true,
            maxlength: 24,
            showWordLimit: true,
            rules: [
              { required: true, message: '请输入用户姓名' },
              { max: 24, message: '最多24个字' },
            ],
            span: 12,
            align: 'left',
            overHidden: true,
          },
          {
            label: '用户来源',
            prop: 'from',
            type: 'select',
            span: 12,
            align: 'left',
            dicData: [
              { label: '默认登录', value: 0 },
              { label: 'ldap登录', value: 1 },
              { label: '单点登录', value: 2 },
              { label: 'Iam登录', value: 3 },
            ],
            overHidden: true,
            showColumn: false,
            display: false,
          },
          {
            label: '手机号码',
            prop: 'phone',
            rules: [
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3-9][0-9]{9}$/, message: '手机号码格式不正确' },
            ],
            span: 12,
            align: 'center',
            hide: true,
            overHidden: true,
          },
          {
            label: '岗位名称',
            prop: 'postId',
            type: 'select',
            props: {
              label: 'postName',
              value: 'id',
            },
            dicUrl: '/api/sys/post/list',
            dicMethod: 'get',
            dicQuery: {},
            showWordLimit: true,
            rules: [{ required: true, message: '请选择岗位名称' }],
            span: 12,
            align: 'left',
          },
          {
            label: '部门',
            prop: 'deptId',
            type: 'tree',
            props: {
              label: 'name',
              value: 'deptId',
            },
            dicUrl: '/api/dept/tree',
            dicMethod: 'post',
            dicQuery: {},
            search: true,
            rules: [{ required: true, message: '请选择所在部门' }],
            addDisabled: false,
            span: 12,
            align: 'left',
            overHidden: true,
          },
          {
            label: '用户角色',
            prop: 'roleIds',
            type: 'select',
            multiple: true,
            props: {
              label: 'name',
              value: 'roleId',
            },
            dicUrl: '/plugin/role/list',
            dicMethod: 'post',
            dicQuery: {},
            rules: [{ required: true, message: '请选择用户角色' }],
            span: 12,
            showColumn: false,
            search: true,
          },
          {
            label: '电子邮箱',
            prop: 'email',
            showWordLimit: true,
            rules: [
              { required: true, message: '请输入电子邮箱' },
              { trigger: 'blur', validator: validateEmail },
            ],
            span: 12,
            showColumn: false,
          },
          {
            label: '用户性别',
            prop: 'gender',
            type: 'switch',
            value: '1',
            hide: true,
            dicData: [
              {
                label: '男',
                value: '1',
              },
              {
                label: '女',
                value: '0',
              },
            ],
            span: 12,
            align: 'center',
            overHidden: true,
          },
          {
            label: '状态',
            prop: 'enabled',
            type: 'switch',
            value: 0,
            dicData: [
              {
                label: '已禁用',
                value: 0,
              },
              {
                label: '已启用',
                value: 1,
              },
            ],
            span: 12,
            align: 'center',
            overHidden: true,
          },
          {
            label: '创建时间',
            prop: 'createTime',
            span: 24,
            width: 150,
            type: 'date',
            searchSpan: 8,
            editDisplay: false,
            addDisplay: false,
            viewDisplay: false,
          },
        ],
      },
      defaultPWD: 'Hyida@2022',
    }
  },
  created() {
    defaultPwd().then((res) => {
      if (res && res.data) {
        this.defaultPWD = res.data
      }
    })
  },
  methods: {
    // 状态
    async onToggleStatus(row) {
      row.switching = true
      const action = row.enabled ? '启用' : '禁用'
      try {
        const { success } = await requestUserStatusUpdate({
          userId: row.userId,
          enabled: Number(!row.enabled),
        })
        if (success) {
          row.enabled = Number(!row.enabled)
          this.$message.success('已' + action)
        } else {
          this.$message.error(action + '失败，请稍后重试')
        }
      } catch (error) {
        console.log(error)
        this.$message.error(action + '出错，请稍后重试')
      }
      row.switching = false
    },
    // 重置密码
    async onPasswordResetClick(row) {
      try {
        await this.$confirm(`重置后密码为：${this.defaultPWD}，确定重置用户【${row.nickName}】的密码?`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      } catch (error) {
        console.log('取消')
        return
      }

      try {
        const { success, message, data } = await requestUserPasswordReset({
          userId: row.userId,
          newPassword: this.defaultPWD,
        })
        if (success) {
          this.$message.success('密码重置成功')
        } else {
          this.$message.error(message)
        }
      } catch (error) {
        this.$message.error('重置密码失败,请稍后重试')
      }
    },
  },
}
</script>

<style lang="scss"></style>
